package com.sz.mes.excel.listener;

import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.ContextHelper;
import com.diboot.core.util.V;
import com.sz.mes.entity.warehouse.Area;
import com.sz.mes.excel.model.GoodsImportModel;
import com.sz.mes.excel.model.ProductTaskImportModel;
import com.diboot.file.excel.listener.FixedHeadExcelListener;
import com.sz.mes.entity.ProductTask;
import com.sz.mes.service.GoodsService;
import com.sz.mes.service.ProductTaskService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 生产任务 导入Listener定义
 *
 * @author hem
 * @version 1.0
 * @date 2024-01-08
 * Copyright © szhs
 */
public class ProductTaskImportListener extends FixedHeadExcelListener<ProductTaskImportModel> {

    private static final String RECEIPT_NUM = BeanUtils.convertToFieldName(ProductTaskImportModel::getReceiptNum);
    private static final String STOCK_NUM = BeanUtils.convertToFieldName(ProductTaskImportModel::getStockNum);

    /**
     * 自定义校验规则
     *
     * @param dataModelList 待保存的数据
     * @param requestParams 请求参数
     */
    @Override
    protected void additionalValidate(List<ProductTaskImportModel> dataModelList, Map<String, Object> requestParams) {
        // 附加校验
        // 对 单据编号、料品编号 是否重复进行校验
        List<String> receiptNumAndStockNumList = new ArrayList<>();
        for (ProductTaskImportModel productTaskImportModel : dataModelList) {
            if (receiptNumAndStockNumList.contains(productTaskImportModel.getReceiptNum()
                    + "-" + productTaskImportModel.getStockNum())) {
                productTaskImportModel.addComment(RECEIPT_NUM, "单据编号重复");
            }
            receiptNumAndStockNumList.add(productTaskImportModel.getReceiptNum()
                    + "-" + productTaskImportModel.getStockNum());

        }
        // 对单据编号及料品编号在系统中是否重复进行校验
        List<String> duplicateList = ContextHelper.getBean(ProductTaskService.class).filterDuplicate(receiptNumAndStockNumList);
        for (String duplicate : duplicateList) {
            dataModelList.get(receiptNumAndStockNumList.indexOf(duplicate)).addComment(RECEIPT_NUM, "该单据编号及备料编号在系统中已存在");
        }
    }

    /**
     * 保存数据
     *
     * @param dataModelList 待保存的数据
     * @param requestParams 请求参数
     */
    @Override
    protected void saveData(List<ProductTaskImportModel> dataModelList, Map<String, Object> requestParams) {
        if (V.isEmpty(dataModelList)) {
            return;
        }
        List<ProductTask> entityList = BeanUtils.convertList(dataModelList, ProductTask.class);
        ContextHelper.getBean(ProductTaskService.class).createEntities(entityList);
    }
}
